package com.gy.controller.result;

import com.alibaba.excel.EasyExcel;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.result.ContinueEducationMaterial;
import com.gy.entity.result.CopyRight;
import com.gy.entity.result.StudentAward;
import com.gy.query.ContinueEducationMaterialQuery;
import com.gy.query.StudentAwardQuery;
import com.gy.result.Result;
import com.gy.service.ContinueEducationMaterialService;
import com.gy.vo.PageVO;
import com.gy.vo.summary.ContinueEducationMaterialVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/cem")
@Api(tags = "继续教育材料接口")
@CrossOrigin
public class ContinueEducationMaterialController {
    @Autowired
    private ContinueEducationMaterialService continueEducationMaterialService;


    /**
     * 根据openid分页查看某个人的继续教育信息
     */
    @PostMapping("/get/personal/award")
    @ApiOperation("根据openid查看某个人的继续教育材料")
    public Result<PageVO<ContinueEducationMaterial>> getPapers(@RequestBody ContinueEducationMaterialQuery continueEducationMaterialQuery){
        return continueEducationMaterialService.getContinueEducationMaterial(continueEducationMaterialQuery);
    }

    /**
     * 根据id主键删除继续教育资料
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据其他id主键删除继续教育材料")
    public Result deleteById(@PathVariable Long id){
        return continueEducationMaterialService.removeContinueEducationMaterialById(id);
    }

    /**
     * 根据id主键查看继续教育资料
     */
    @GetMapping("/get/cem/ById/{id}")
    @ApiOperation("根据id主键查看继续教育资料")
    public Result<ContinueEducationMaterial> getContinueEducationMaterialById(@PathVariable Long id){
        ContinueEducationMaterial continueEducationMaterial= continueEducationMaterialService.getContinueEducationMaterialById(id);
        return Result.success(continueEducationMaterial);
    }

    /**
     * 更改继续教育资料
     */
    @PutMapping("/update")
    @ApiOperation("更改继续教育资料")
    public Result update(@RequestBody ContinueEducationMaterial continueEducationMaterial){
        return continueEducationMaterialService.updateContinueEducationMaterial(continueEducationMaterial);
    }

    /**
     * 新增继续教育资料
     */
    @PostMapping("/save")
    @ApiOperation("新增继续教育资料")
    public Result save(@RequestBody ContinueEducationMaterial continueEducationMaterial){
        return continueEducationMaterialService.saveContinueEducationMaterial(continueEducationMaterial);
    }

    /**
     * 根据id批量查询数据
     */
    @PostMapping("/getByIds")
    @ApiOperation("根据多个id查询继续教育资料")
    public Result getByIds(@RequestBody Long[] ids){
        return continueEducationMaterialService.getContinueEducationMaterialBatchIds(ids);
    }

    /**
     * excel批量导出
     */
    @PostMapping("/export")
    @ApiOperation("excel批量导出")
    public void exportPersonalAward(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_ContinueEducationMaterial.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("ContinueEducationMaterial")
                .doWrite(transformedData);
    }

    /**
     * 汇总表格中返回继续教育材料信息
     */
    @GetMapping("/getSummary")
    @ApiOperation("汇总表格中返回继续教育材料信息")
    public Result<List<ContinueEducationMaterialVO>> getSummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户登录信息异常");
        }

        // 查询并选择 ContinueEducationMaterialVO 中的字段
        List<ContinueEducationMaterial> list = continueEducationMaterialService.lambdaQuery()
                .eq(ContinueEducationMaterial::getUserId, userId)
                .select(
                        ContinueEducationMaterial::getTitle,
                        ContinueEducationMaterial::getHours,
                        ContinueEducationMaterial::getScore,
                        ContinueEducationMaterial::getObtainTime,
                        ContinueEducationMaterial::getTrainingUnit
                )
                .list();

        // 将查询结果转换为 ContinueEducationMaterialVO 列表
        List<ContinueEducationMaterialVO> voList = list.stream()
                .map(cem -> ContinueEducationMaterialVO.builder()
                        .title(cem.getTitle())
                        .hours(cem.getHours())
                        .score(cem.getScore())
                        .obtainTime(cem.getObtainTime())
                        .trainingUnit(cem.getTrainingUnit())
                        .build())
                .collect(Collectors.toList());

        return Result.success(voList);
    }

}

